package com.atguigu.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @author: 叶子
 * @date: 2022/08/14 21:41
 * 提高生产者吞吐量，可以通过设置4个参数来实现
 * 缓冲区大小、批次大小、linger.ms、压缩类型
 **/
public class CustomProducerParameters {
    public static void main(String[] args) {
        //0 配置信息
        Properties properties = new Properties();
        //连接kafka集群
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"kafka130:9092,kafka131:9093,kafka132:9094");
        //序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());
        //为了提高吞吐量，需要配置4个参数
        // 缓冲区大小
        properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG,33554432);
        // 批次大小
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG,16384);
        // linger.ms
        properties.put(ProducerConfig.LINGER_MS_CONFIG,20);
        // 压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");
        //1 创建生产者
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
        //2 发送数据
        for (int i = 0; i <5; i++) {
            kafkaProducer.send(new ProducerRecord<>("firstTopi ","dage"+i));
        }
        //3 关闭资源
        kafkaProducer.close();
    }
}